package com.controller;

import com.model._do.DoctorAuthDO;
import com.model._do.UserDO;
import com.model.dto.baseDTO.ResultDTO;
import com.service.DoctorAuthService;
import com.service.ResultService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private ResultService resultService;

    @Autowired
    private DoctorAuthService doctorAuthService;

    /**
     * 根据user获取doctorAuth信息
     * @param doctor user信息
     * @return auth表元组
     */
    @RequestMapping(value = "/getDoctorAuthInfo", method = RequestMethod.POST)
    public ResultDTO getDoctorAuth(@RequestBody UserDO doctor){
        return resultService.createSuccess("success", doctorAuthService.getDoctorByUserId(doctor));
    }


    @RequestMapping("/uploadImage")
    public ResultDTO uploadAuth(@RequestParam("file") MultipartFile file, DoctorAuthDO auth, HttpServletRequest req) throws IOException {
        if (file.isEmpty()) {
            return resultService.createFailed("failed");
        }
        try{
            doctorAuthService.upLoadAuthFile(file, auth, req);
            return resultService.createSuccess("success");
        } catch (Exception e){
            e.printStackTrace();
            return resultService.createFailed("错误，具体看日志");
        }
    }

    @RequestMapping(value = "/downloadImage")
    public String download(@RequestParam("authPath") String authPath , HttpServletResponse res) throws Exception {
        String imgPath = authPath;
        File file = new File(imgPath);
        InputStream is = new BufferedInputStream(new FileInputStream(file));
        byte [] buffer = new byte[is.available()];
        is.read(buffer);
        is.close();
        OutputStream os = res.getOutputStream();
        os.write(buffer);
        res.addHeader("Content-Disposition","attachment;filename=myAuth");
        res.setContentType("application/octet-stream");
        res.addHeader("Content-Length", String.valueOf(file.length()));
        os.flush();
        os.close();
        is.close();
        return null;
    }
}
